package endpoint

import (
	"consul_grpc/service"
	"context"

	"github.com/go-kit/kit/endpoint"
)

//相应服务端点的处理方法集
type ConsulGrpcEndpoint struct {
	GreetEndpoint     endpoint.Endpoint
	HealthEndpoint    endpoint.Endpoint
	DiscoveryEndpoint endpoint.Endpoint
}

// HealthRequest 健康检查请求结构  //该健康检查无法直接使用，抛弃！！！！
type HealthRequest struct{}

// HealthResponse 健康检查响应结构
type HealthResponse struct {
	Status bool `json:"Status"`
}

//建立健康检查的端点处理方法
func MakeHealthCheckEndpoint(srv service.Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		status := true
		return HealthResponse{Status: status}, nil
	}
}

//以下同样操作建立Request和Response，以及对应的端点处理方法

type GreetRequest struct {
	Name string `json:"Name"`
}
type GreetResponse struct {
	Reply string `json:"Reply"`
}

func MakeGreetEndpoint(srv service.Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		//将grpc请求参数转换成当前所用的结构
		req := request.(GreetRequest)
		//调用逻辑层的具体实现方法
		reply := srv.Greet(req.Name)
		return GreetResponse{
			Reply: reply,
		}, nil
	}
}

type DiscoveryRequest struct {
	ServiceName string `json:"ServiceName"`
}

type DiscoveryResponse struct {
	ResBuf string `json:"ResBuf"`
	Error  string `json:"Error"`
}

func MakeDiscoveryEndpoint(srv service.Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		req := request.(DiscoveryRequest)
		res, err := srv.Discovery(req.ServiceName)
		if err != nil {
			return DiscoveryResponse{
				ResBuf: res,
				Error:  err.Error(),
			}, nil
		}
		return DiscoveryResponse{
			ResBuf: res,
			Error:  "",
		}, nil
	}
}
